package com.adnaan.backend.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.AfterSales;
import com.adnaan.backend.entity.Order;
import com.adnaan.backend.entity.vo.HandleAfterSalesVo;
import com.adnaan.backend.service.AfterSalesService;
import com.adnaan.backend.service.OrderService;
import com.adnaan.backend.service.SupplierApplicationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestControllerMapping("/after-sales")
@Tag(name = "售后管理", description = "售后管理")
@ApiSupport(author = "adnaan", order = 2)
public class AfterSalesController {

    @Resource
    private AfterSalesService afterSalesService;

    @Resource
    private OrderService orderService;

    @Resource
    private SupplierApplicationService supplierApplicationService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @GetMapping("/info/{id}")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "通过ID查询单条数据")
    public Result<AfterSales> getById(@PathVariable Long id) {
        return Result.success(afterSalesService.getById(id));
    }

    /**
     * 分页查询
     *
     * @param pageParams 分页对象
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页查询")
    public Result<Page<AfterSales>> pageQuery(@RequestBody PageParams<AfterSales> pageParams) {
        AfterSales params = pageParams.getParams();
        LambdaQueryWrapper<AfterSales> lqw = new LambdaQueryWrapper<>();
        // 如果是供货商，只能查看自己的售后
        Long userId = StpUtil.getLoginIdAsLong();
        if (supplierApplicationService.isSupplier(userId)) {
            // 通过订单关联查询供货商的售后
            lqw.inSql(AfterSales::getOrderId,
                    "SELECT id FROM order_list WHERE supplier_id = " + userId);
        }
        lqw.eq(params.getStatus() != null, AfterSales::getStatus, params.getStatus())
                .eq(params.getType() != null, AfterSales::getType, params.getType())
                .orderByDesc(AfterSales::getCreateTime);
        return Result.success(afterSalesService.page(pageParams.getPage(), lqw));
    }

    /**
     * 处理售后申请
     *
     * @param afterSalesVo (id         售后ID
     *                     status     状态：0-待处理 1-处理中 2-已完成 3-已拒绝
     *                     handleNote 处理备注)
     * @return 是否成功
     */
    @PostMapping("/handle")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "处理售后申请")
    public Result<Boolean> handleAfterSales(@RequestBody HandleAfterSalesVo afterSalesVo) {
        // 检查是否是供货商的售后
        AfterSales afterSales = afterSalesService.getById(afterSalesVo.getId());
        if (afterSales == null) {
            return Result.error("售后申请不存在");
        }
        Order order = orderService.getById(afterSales.getOrderId());
        if (order == null) {
            return Result.error("关联订单不存在");
        }
        return Result.success(afterSalesService.handleAfterSales(afterSalesVo.getId(), afterSalesVo.getStatus(), afterSalesVo.getHandleNote()));
    }

    /**
     * 检查订单是否可以申请售后
     *
     * @param orderId 订单ID
     * @return 是否可以申请
     */
    @GetMapping("/check/{orderId}")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "检查订单是否可以申请售后")
    public Result<Boolean> checkAfterSales(@PathVariable Long orderId) {
        // 检查是否是订单的所有者
        Order order = orderService.getById(orderId);
        if (order == null) {
            return Result.error("订单不存在");
        }
        return Result.success(afterSalesService.canApplyAfterSales(orderId));
    }
} 